package com.example.homework.viewmodels

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.example.homework.adapters.CharactSource
import com.example.homework.db.apis.RetrofitService
import com.example.homework.db.models.Charact
import com.example.homework.db.models.Episode
import com.example.homework.db.repositories.CharactRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class CharacterViewModel : ViewModel() {
    private val charactRepository: CharactRepository = CharactRepository()
    val characters: Flow<PagingData<Charact>> = Pager(PagingConfig(pageSize = 20)) {
        CharactSource(charactRepository)
    }.flow

    private val _character = MutableStateFlow<Charact?>(null)
    val character: StateFlow<Charact?> = _character.asStateFlow()

    private val _episodes = MutableStateFlow<List<Episode>>(emptyList())
    val episodes: StateFlow<List<Episode>> = _episodes.asStateFlow()

    fun loadCharacter(characterId: Int) {
        viewModelScope.launch {
            try {
                val charact = RetrofitService.charactersApi.getOne(characterId)
                _character.value = charact

                val episodeIds = charact.episode.map { it.substringAfterLast("/") }
                val episodesList = episodeIds.map { RetrofitService.episodesApi.getOne(it.toInt()) }
                _episodes.value = episodesList
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
}